package com.zj.leetcode.easy;

/**
 * @program: algorithm
 * @description: 移除链表元素
 * 203 remove-linked-list-elements
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class RemoveLinkedListElements {
    public static void main(String[] args) {
        Solution solution = new RemoveLinkedListElements().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode() {}
     * ListNode(int val) { this.val = val; }
     * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    class Solution {
        public ListNode removeElements(ListNode head, int val) {

            //以防头结点被删除
            ListNode headNode = new ListNode(-1);
            headNode.next = head;

            //临时节点 用作遍历
            ListNode temp = headNode;
            while (temp.next != null) {

                if (temp.next.val == val) {
                    temp.next = temp.next.next;
                } else {
                    temp = temp.next;
                }

            }

            return headNode.next;
        }


        public ListNode removeElements01(ListNode head, int val) {
            if (head == null) {
                return head;
            }
            head.next = removeElements01(head.next, val);
            return head.val == val ? head.next : head;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}